<template>
  <div class="history-panel">
    <div class="panel-header">

      <el-button type="success" size="large" class="action-button" @click="createNewProject">
        <el-icon>
          <ChatLineRound />
        </el-icon>
        <span>开始新会话</span>
      </el-button>
      <!-- <div class="header-actions" v-if="historyRecords.length > 0">
        <el-tooltip content="清空所有记录" placement="top">
          <el-button type="danger" :icon="Delete" circle size="small" @click="confirmClearHistory" />
        </el-tooltip>
      </div> -->
    </div>

    <div v-if="historyRecords.length === 0" class="empty-state">
      <el-empty description="暂无历史记录" :image-size="100">
        <template #image>
          <el-icon class="empty-icon">
            <DocumentRemove />
          </el-icon>
        </template>
        <span class="empty-text">您的项目历史记录将显示在这里</span>
      </el-empty>
    </div>

    <div v-else class="history-list">
      <TransitionGroup name="history-item">
        <div v-for="(record, index) in historyRecords" :key="record.id" class="history-item"
          :class="{ 'active': historyRecord?.id === record.id }" @click="selectHistory(record)">
          <div class="item-header">
            <div class="item-title">
              <!-- <el-tag size="small" effect="dark" class="step-tag" :type="getStepTagType(record)">
                {{ displayCurrentStep(record) }}
              </el-tag> -->
              <span class="requirement-title">{{ record.prompt ? record.prompt.slice(0, 30) + (record.prompt.length > 30
                ?
                '...' : '') : record.response ? record.response.slice(0, 30) + (record.response.length > 30 ? '...' :
                  '') :
                '新项目' }}</span>
            </div>
            <div class="item-actions">
              <el-tooltip content="删除此记录" placement="top">
                <el-button type="danger" :icon="Delete" circle plain size="small"
                  @click.stop="confirmDeleteHistory(record)" />
              </el-tooltip>
            </div>
          </div>

          <div class="item-content">
            <div class="progress-stages">
              <div v-for="(stage, stageIndex) in stages" :key="stageIndex" class="stage" :class="{
                'completed': isStageCompleted(record, stageIndex),
                'current': isCurrentStage(record, stageIndex)
              }">
                <div class="stage-dot">
                  <el-icon v-if="isStageCompleted(record, stageIndex)" class="success-icon">
                    <Check />
                  </el-icon>
                  <span v-else class="dot-number">{{ stageIndex + 1 }}</span>
                </div>
                <div class="stage-line" v-if="stageIndex < stages.length - 1"></div>
              </div>
            </div>
            <div class="stage-labels">
              <div v-for="(stage, stageIndex) in stages" :key="stageIndex" class="stage-label" :class="{
                'completed': isStageCompleted(record, stageIndex),
                'current': isCurrentStage(record, stageIndex)
              }">
                {{ stage }}
              </div>
            </div>
          </div>

          <div class="item-footer">
            <span class="timestamp">{{ formatDate(record.timestamp) }}</span>
          </div>
        </div>
      </TransitionGroup>
    </div>

    <!-- 确认删除对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="确认删除" width="400px" align-center destroy-on-close>
      <span>确定要删除这条历史记录吗？此操作不可恢复。</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteHistory">确认删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认清空对话框 -->
    <el-dialog v-model="clearDialogVisible" title="确认清空" width="400px" align-center destroy-on-close>
      <span>确定要清空所有历史记录吗？此操作不可恢复。</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="clearDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="clearHistory">确认清空</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useHistoryStore } from '../stores/history';
import { Delete, Calendar, DocumentRemove, Check } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus';
import { getHistoryItems } from '@/api/llm';
import { getProjectDescription } from '@/api/llm';
import { getWorkflow } from '@/api/llm';
// 创建新项目

async function getHistories() {
  const historyItems = await getHistoryItems();
  const newHistoryList = []; // 用于存储所有新的历史记录

  for (const item of historyItems) {
    const id = item.intention_id;
    const prompt = item.intention;
    const timestamp = item.updated_at;
    const response = await getProjectDescription(id);
    response.intentionID = id

    const newHistory = {
      id,
      prompt,
      response,
      timestamp,
      step: 'requirement',
      workflow: null,
      code: '',
      deployGuide: ''
    };

    newHistoryList.push(newHistory);
  }

  // 一次性更新整个列表
  historyStore.historyList = [...historyStore.historyList, ...newHistoryList];
}

const historyStore = useHistoryStore();
getHistories()
const createNewProject = () => {
  historyStore.createNewChat();
  promptInput.value = '';
};

// 获取历史记录列表并按id排序
const historyRecords = computed(() => {
  return historyStore.historyList.slice().sort((a, b) => b.id - a.id);
});

// 当前选中的历史记录
const historyRecord = computed(() => historyStore.activeHistory);

// 选择历史记录
const selectHistory = (record) => {
  historyStore.setActiveHistory(record.id);
};

// 删除对话框状态
const deleteDialogVisible = ref(false);
const clearDialogVisible = ref(false);
const historyToDelete = ref(null);

// 确认删除单条历史
const confirmDeleteHistory = (record) => {
  historyToDelete.value = record;
  deleteDialogVisible.value = true;
};

// 删除单条历史
const deleteHistory = () => {
  if (historyToDelete.value) {
    historyStore.removeHistory(historyToDelete.value.id);
    deleteDialogVisible.value = false;
    historyToDelete.value = null;
  }
};

// 确认清空所有历史
const confirmClearHistory = () => {
  clearDialogVisible.value = true;
};

// 清空所有历史
const clearHistory = () => {
  // 确保historyStore有clearHistory方法
  if (typeof historyStore.clearHistory === 'function') {
    historyStore.clearHistory();
  } else {
    // 如果没有，则遍历删除所有历史
    historyStore.historyList.forEach(record => {
      historyStore.removeHistory(record.id);
    });
  }
  clearDialogVisible.value = false;
};

// 格式化日期
const formatDate = (timestamp) => {
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now - date;

  // 小于一分钟显示"刚刚"
  if (diff < 60 * 1000) {
    return '刚刚';
  }

  // 小于一小时显示"xx分钟前"
  if (diff < 60 * 60 * 1000) {
    return Math.floor(diff / (60 * 1000)) + '分钟前';
  }

  // 小于24小时显示"xx小时前"
  if (diff < 24 * 60 * 60 * 1000) {
    return Math.floor(diff / (60 * 60 * 1000)) + '小时前';
  }

  // 今年内显示"MM-DD HH:mm"
  if (date.getFullYear() === now.getFullYear()) {
    return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  }

  // 超过一年显示完整日期"YYYY-MM-DD HH:mm"
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 阶段定义
const stages = ['需求分析', '工作流设计', '代码生成', '部署指南'];

// 显示当前步骤文本
const displayCurrentStep = (record) => {
  if (!record) return '需求分析';
  if (record.deployGuide) return '部署指南';
  if (record.code) return '代码生成';
  if (record.workflow) return '工作流设计';
};

// 获取步骤标签类型
const getStepTagType = (record) => {
  if (!record) return '';

  if (record.deployGuide) return 'success';
  if (record.code) return 'warning';
  if (record.workflow) return 'info';
  return 'primary';
};

// 检查阶段是否已完成
const isStageCompleted = (record, stageIndex) => {
  if (!record) return false;

  switch (stageIndex) {
    case 0: return true; // 需求分析总是完成的
    case 1: return !!record.workflow;
    case 2: return !!record.code;
    case 3: return !!record.deployGuide;
    default: return false;
  }
};

// 检查是否为当前阶段
const isCurrentStage = (record, stageIndex) => {
  if (!record) return stageIndex === 0;

  if (!record.workflow) return stageIndex === 1;
  if (!record.code) return stageIndex === 2;
  if (!record.deployGuide) return stageIndex === 3;
  return stageIndex === 4; // 如果全部完成，当前阶段为最后一个
};
</script>

<style scoped>
.history-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.panel-header {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  background-color: #f8fafc;
  border-bottom: 1px solid #ebeef5;
}

.header-icon {
  font-size: 22px;
  margin-right: 10px;
  color: #409eff;
}

.panel-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
  font-weight: 600;
  flex: 1;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  height: 100%;
}

.empty-icon {
  font-size: 60px;
  color: #909399;
  margin-bottom: 16px;
}

.empty-text {
  color: #909399;
  font-size: 14px;
  margin-top: 12px;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.history-item {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f8f9fa;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.history-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.history-item.active {
  background-color: #ecf5ff;
  border-color: #a0cfff;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.item-title {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.step-tag {
  width: fit-content;
}

.requirement-title {
  font-weight: 500;
  color: #303133;
  padding-left: 2px;
}

.item-actions {
  opacity: 0;
  transition: opacity 0.2s ease;
}

.history-item:hover .item-actions {
  opacity: 1;
}

.item-content {
  margin-top: 16px;
}

.progress-stages {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.stage {
  display: flex;
  align-items: center;
  position: relative;
}

.stage-dot {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 12px;
  font-weight: bold;
  transition: all 0.3s ease;
  z-index: 1;
}

.stage.completed .stage-dot {
  background-color: #67c23a;
  color: #fff;
}

.stage.current .stage-dot {
  background-color: #409eff;
  color: #fff;
  box-shadow: 0 0 0 4px rgba(64, 158, 255, 0.2);
}

.success-icon {
  font-size: 14px;
  color: #fff;
}

.dot-number {
  font-size: 12px;
}

.stage-line {
  height: 2px;
  background-color: #e4e7ed;
  flex: 1;
  min-width: 30px;
  margin: 0 4px;
  transition: background-color 0.3s ease;
}

.stage.completed .stage-line {
  background-color: #67c23a;
}

.stage-labels {
  display: flex;
  justify-content: space-between;
  margin-top: 4px;
}

.stage-label {
  width: 25%;
  text-align: center;
  font-size: 12px;
  color: #909399;
  padding: 0 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: color 0.3s ease;
}

.stage-label.completed {
  color: #67c23a;
}

.stage-label.current {
  color: #409eff;
  font-weight: bold;
}

.item-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
  padding-top: 8px;
  border-top: 1px dashed #ebeef5;
}

.timestamp {
  font-size: 12px;
  color: #909399;
}

/* 列表动画 */
.history-item-enter-active,
.history-item-leave-active {
  transition: all 0.5s ease;
}

.history-item-enter-from {
  opacity: 0;
  transform: translateX(-20px);
}

.history-item-leave-to {
  opacity: 0;
  transform: translateX(20px);
}
</style>